App.require(function () {
    var app = App.getCurrent();
    var createImageUid = (function () {
        var uid = 0;
        return function () {
            return "imageId" + (uid++);
        }
    }());

    app.definePage("createViewer", {
        render: function (next) {
            this.data.selectId = [];
            this.data.currentIndex = undefined;
            this.data.scenes = this.parent.data.scenes;
            this.fetch("./index.html", function (text) {
                next(this.renderHTML(text));
            })
        },
        getDomObj: function () {
            this.attachDom(".btn-group", "btnGroup")
                .attachDom(".create-scene-list", "list")
                .attachDom("#viewer", "viewer")
                .attachDom("#sceneManager", "sceneManager")
                .attachEvent("sceneManager", "scenedelete", this.deleteSceneHandler, false)
                .attachDiyEvent("addSceneByName", this.addNameSceneHandler)
                .attachEvent("sceneManager", "sceneObjplus", this.sceneObjPlusHandler, false)
                .attachEvent("sceneManager", "itemclick", this.sceneItemClickHandler, false)
                .attachEvent("list", "click", this.clickSceneListHandler, false)
                .attachEvent("btnGroup", "btnclick", this.btnClickHandler, false);
        },
        sceneItemClickHandler: function (ev) {
            console.log(ev);
            this.data.currentIndex = ev.detail.index;
            this.domList.sceneViewer.previewScene(ev.detail.scene.scenes, app.wm, app.wbm);
        },
        deleteSceneHandler: function (ev) {
            console.log(ev);
        },
        addNameSceneHandler: function (ev) {
            this.domList.sceneManager.addSceneByName(ev.name, ev.description);
            this.data.selectId.push([]);
            if (typeof this.data.currentIndex === "undefined") this.data.currentIndex = 0;
            else this.data.currentIndex++;
            this.domList.sceneViewer._clear();
            ev.popup.hidden();
        },
        sceneObjPlusHandler: function (ev) {
            this.showPageDialog("addSceneObj", {
                mask: true, maskCancel: false,
                cssString: "--startstatus: scale(0);--endstatus: scale(1); width: 400px; height: 350px;"
            })
        },
        clickSceneListHandler: function (ev) {
            if (typeof this.data.currentIndex !== "undefined") {
                var div = Component.getNodeName(ev.target, "DIV");
                var id = div.dataset.id;
                if (id) {
                    var selectId = this.data.selectId[this.data.currentIndex];
                    var index = selectId.indexOf(id)
                    if (index !== -1) selectId.splice(index, 1);
                    else selectId.push(id);
                }
                var scenes = this.getSelectScenes();
                this.domList.sceneViewer.previewScene(scenes, app.wm, app.wbm);
            }
        },
        getSelectScenes: function () {
            var ids = this.data.selectId[this.data.currentIndex], 
                scenes = [];
            for (var i = 0; i < ids.length; i++) {
                var scene = this.getSceneByUid(ids[i]);
                scenes.push(scene);
            }
            return scenes;
        },
        getSceneByUid: function (id) {
            var scenes = this.data.scenes;
            for (var i = 0; i < scenes.length; i++) {
                if (scenes[i].uid == id) return scenes[i];
            }
        },
        init: function () {
            this.domList.sceneViewer = App.Viewer.create(this.domList.viewer, { width: 960, height: 540 }, app.sm, "index", {})
        },
        getResourceByValue: function (obj, value) {
            for (var key in obj) {
                if (obj[key] == value) return {
                    key: key, value: value
                }
            }
        },
        createViewObj() {
            var selectScenes = this.domList.sceneManager.getScenes(),
                scenes = JSON.parse(JSON.stringify(this.data.scenes)),
                canvas = this.domList.sceneViewer.canvas;

            var result = { 
                width: canvas.width,
                height: canvas.height,
                scenes: [], 
                selectScenes: [], 
                resources: {}, 
                markers: {}
            };
            var widgets = [];
            for (var i = 0; i < scenes.length; i++) {
                var scene = scenes[i];
                for (var j = 0; j < scene.widgets.length; j++) {
                    var widget = scene.widgets[j], resourceKey = widget.resourceKey;
                    if (resourceKey) {
                        for (var k = 0; k < resourceKey.length; k++) {
                            var rk = resourceKey[k];
                            if (widget.style[rk.key]) {
                                widget.style = JSON.parse(JSON.stringify(widget.style));
                                if (!result.resources[rk.type]) result.resources[rk.type] = {};
                                var value = widget.style[rk.key];
                                var obj = this.getResourceByValue(result.resources[rk.type], value);
                                if (obj) {
                                    widget.style[rk.key] = obj.key;
                                }
                                else {
                                    var uid = createImageUid();
                                    result.resources[rk.type][uid] = widget.style[rk.key];
                                    widget.style[rk.key] = uid;
                                }
                            }
                        }
                    }
                    widgets.push(widget);
                }
                for (var key in scene.marker) {
                    result.markers[key] = scene.marker[key];
                }
                result.scenes.push(scene);
            }

            for (var i = 0; i < selectScenes.length; i++) {
                var sceneObj = selectScenes[i];
                result.selectScenes.push({
                    description: sceneObj.description,
                    title: sceneObj.title,
                    uid: sceneObj.uid,
                    scenes: sceneObj.scenes.map(function (item) {
                        return item.uid
                    })
                })
            }

            return result;
        },
        btnClickHandler: function (ev) {
            var component = ev.detail.component;
            switch (component.dataset.action) {
                case "create":
                    console.log(this.createViewObj());
                    break;
                case "save": 
                    var scenes = this.getSelectScenes();

                    this.domList.sceneManager.saveScenes(scenes, this.domList.sceneViewer.createUrl())
                    break;
                case "close": this.parent.hidden(); break;
            }
        }
    })
})